// select-course.js
import Toast from '@vant/weapp/toast/toast';
import { getCourseSelectList, selectCourse } from '../../utils/api-v2';

Page({
  data: {
    searchKeyword: '',
    courseList: []
  },

  onLoad() {
    this.loadCourseList();
  },

  // 加载课程列表
  loadCourseList() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });

    // 调用接口 GET /student/course/select/page/1
    getCourseSelectList(1)
      .then((res) => {
        Toast.clear();
        let courseList = res.data || [];
        
        console.log('========== 选课列表 完整 API 返回 ==========');
        console.log('完整响应:', JSON.stringify(res, null, 2));
        console.log('========== 第一个课程的所有字段 ==========');
        if (courseList[0]) {
          Object.keys(courseList[0]).forEach(key => {
            console.log(`${key}: ${courseList[0][key]}`);
          });
        }
        console.log('==========================================');
        
        // 统一字段名：将 courseId/cid/studentCourseId 等转换为 id
        courseList = courseList.map(item => {
          // 查找有效的 ID 字段
          const validId = item.courseId || item.cid || item.course_id || item.studentCourseId;
          
          // 格式化时间: "2-2-4" => "周二 2-4节"
          const rawTime = item.time || item.courseTime || '';
          let formattedTime = rawTime || '待安排';
          if (formattedTime && formattedTime !== '待安排') {
            formattedTime = this.formatTime(formattedTime);
          }
          
          // 补充缺失的字段，提供默认值
          return {
            ...item,
            id: validId,
            rawTime,
            time: formattedTime,
            location: item.location || item.courseLocation || '待定',
            selectedCount: item.selectedCount || item.currentNum || 0,
            maxCount: item.maxCount || item.maxNum || 50
          };
        });
        
        console.log('转换后第一个课程:', courseList[0]);
        console.log('转换后 id 值:', courseList[0]?.id);
        console.log('转换后 time 值:', courseList[0]?.time);
        
        this.setData({ courseList });
      })
      .catch((err) => {
        Toast.clear();
        console.error('加载课程列表失败:', err);
        Toast.fail('加载失败，请稍后重试');
      });
  },

  // 搜索输入变化
  onSearchChange(e) {
    this.setData({
      searchKeyword: e.detail
    });
  },

  // 搜索
  onSearch() {
    const { searchKeyword } = this.data;
    if (!searchKeyword) {
      this.loadCourseList();
      return;
    }

    Toast('搜索功能开发中...');
  },

  // 选课
  selectCourse(e) {
  const courseId = e.currentTarget.dataset.id;
  const course = this.data.courseList.find(item => String(item.id) === String(courseId));
    
    console.log('===== 选课调试 =====');
    console.log('点击选课，courseId:', courseId);
    console.log('dataset:', e.currentTarget.dataset);
    console.log('当前课程列表:', this.data.courseList);
    if (this.data.courseList && this.data.courseList.length > 0) {
      console.log('第一个课程:', this.data.courseList[0]);
      console.log('第一个课程的所有字段:', Object.keys(this.data.courseList[0]));
    }
    console.log('==================');
    
    if (!courseId || !course) {
      Toast.fail('课程ID不存在，请刷新页面重试');
      return;
    }

    if (course.isSelected) {
      Toast('已选择该课程');
      return;
    }

    const conflictCourse = this.findTimeConflict(course);
    if (conflictCourse) {
      const conflictName = conflictCourse.courseName || conflictCourse.name || '已选课程';
      const conflictTime = conflictCourse.time || conflictCourse.rawTime || '';
      Toast.fail(`与 ${conflictName} (${conflictTime}) 时间冲突`);
      return;
    }
    
    wx.showModal({
      title: '确认选课',
      content: '确定要选择这门课程吗？',
      success: (res) => {
        if (res.confirm) {
          this.confirmSelect(courseId);
        }
      }
    });
  },

  // 确认选课
  confirmSelect(courseId) {
    console.log('确认选课，courseId:', courseId);
    
    Toast.loading({
      message: '选课中...',
      forbidClick: true,
      duration: 0
    });

    // 调用接口 POST /student/course/select/:id
    selectCourse(courseId)
      .then((res) => {
        Toast.clear();
        Toast.success('选课成功');

        // 更新课程状态
        const { courseList } = this.data;
        const index = courseList.findIndex(item => String(item.id) === String(courseId));
        if (index !== -1) {
          courseList[index].isSelected = true;
          courseList[index].selectedCount++;
          this.setData({ courseList });

          // 同时保存到本地存储（用于课表显示）
          const selectedCourse = courseList[index];
          let myCourses = wx.getStorageSync('myCourses') || [];
          
          const exists = myCourses.some(course => course.id === selectedCourse.id);
          if (!exists) {
            myCourses.push({
              id: selectedCourse.id,
              courseName: selectedCourse.courseName,
              teacherName: selectedCourse.teacherName,
              time: selectedCourse.time,
              rawTime: selectedCourse.rawTime || selectedCourse.time,
              credit: selectedCourse.credit,
              location: selectedCourse.location,
              score: null,
              selectDate: new Date().toISOString().split('T')[0]
            });
            wx.setStorageSync('myCourses', myCourses);
          }
        }
      })
      .catch((err) => {
        Toast.clear();
        Toast.fail(err.msg || '选课失败');
        console.error('选课失败:', err);
      });
  },

  /**
   * 格式化时间字符串
   * @param {string} timeStr - 原始时间 "4-5-4"
   * @returns {string} - 格式化后 "周四 5-8节"
   */
  formatTime(timeStr) {
    if (!timeStr) return '待安排';
    
    // 已经是中文格式，直接返回
    if (timeStr.includes('周')) {
      return timeStr;
    }
    
    // 解析 "4-5-4" 格式：周4，第5节开始，上4节课
    const match = timeStr.match(/^(\d+)-(\d+)-(\d+)$/);
    if (match) {
      const day = parseInt(match[1]);
      const startSlot = parseInt(match[2]);
      const duration = parseInt(match[3]);
      const endSlot = startSlot + duration - 1;
      
      const weekDays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      const weekDay = weekDays[day] || '周?';
      
      return `${weekDay} ${startSlot}-${endSlot}节`;
    }
    
    return timeStr;
  },

  findTimeConflict(targetCourse) {
    const targetSlots = this.extractCourseSlots(targetCourse.rawTime || targetCourse.time);
    if (!targetSlots) return null;

    const comparedList = [];
    const localCourses = wx.getStorageSync('myCourses') || [];
    comparedList.push(...localCourses);
    this.data.courseList.forEach(item => {
      if (item.isSelected) {
        comparedList.push(item);
      }
    });

    return comparedList.find(existing => {
      if (!existing) return false;
      if (existing.id && String(existing.id) === String(targetCourse.id)) {
        return false;
      }
      const existingSlots = this.extractCourseSlots(existing.rawTime || existing.time);
      if (!existingSlots) return false;
      if (existingSlots.dayIndex !== targetSlots.dayIndex) return false;
      return existingSlots.sections.some(section => targetSlots.sections.includes(section));
    }) || null;
  },

  extractCourseSlots(timeStr) {
    if (!timeStr) return null;

    // 数字格式：4-5-4
    const numericMatch = timeStr.match(/^(\d+)-(\d+)-(\d+)$/);
    if (numericMatch) {
      const day = parseInt(numericMatch[1], 10);
      const start = parseInt(numericMatch[2], 10);
      const duration = parseInt(numericMatch[3], 10);
      const sections = [];
      for (let i = 0; i < duration; i++) {
        const section = start + i;
        if (section >= 1 && section <= 10) {
          sections.push(section);
        }
      }
      if (sections.length === 0) return null;
      return {
        dayIndex: day - 1,
        sections
      };
    }

    const weekDayMap = {
      '周一': 0,
      '周二': 1,
      '周三': 2,
      '周四': 3,
      '周五': 4,
      '周六': 5,
      '周日': 6
    };

    const zhMatch = timeStr.match(/(周[一二三四五六日])\s*(\d+)-(\d+)节/);
    if (zhMatch) {
      const dayIndex = weekDayMap[zhMatch[1]];
      if (dayIndex === undefined) return null;
      const startSection = parseInt(zhMatch[2], 10);
      const endSection = parseInt(zhMatch[3], 10);
      if (isNaN(startSection) || isNaN(endSection)) return null;
      const sections = [];
      for (let section = startSection; section <= endSection; section++) {
        if (section >= 1 && section <= 10) {
          sections.push(section);
        }
      }
      if (sections.length === 0) return null;
      return { dayIndex, sections };
    }

    return null;
  }
});
